from sqlalchemy import (
    Column,
    Integer,
    String,
    Boolean,
    ForeignKey,
    DateTime,
)
from sqlalchemy.orm import relationship
from datetime import datetime
from src.db_models.base import db

class User(db.Model):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True, autoincrement=True)
    nickname = Column(String(50), nullable=False)
    email = Column(String(120), unique=True, nullable=False)
    password = Column(String(128), nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow)
    # User 表和 TermCollection 表之间存在多个外键(user_id 和 origin_user_id)- 指定外键 user_id 作为用户拥有的术语集
    # 与术语集表建立关系
    term_collections = relationship('TermCollection', backref='user', lazy=True, foreign_keys='TermCollection.user_id')

    def __repr__(self):
        return f"<User(email={self.email}, nickname={self.nickname})>"

    def to_dict(self):
        return {
            'id': self.id,
            'nickname': self.nickname,
            'email': self.email
        }

# 术语集表
class TermCollection(db.Model):
    __tablename__ = 'term_collections'

    id = Column(Integer, primary_key=True, autoincrement=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)  # 当前拥有者
    origin_user_id = Column(Integer, ForeignKey('users.id'), nullable=False)  # 原始创建者
    table_name = Column(String(100), nullable=False)
    category = Column(String(50), nullable=True)  # 术语集分类，例如“治国理政”、“物理学”
    is_public = Column(Boolean, default=False)  # 是否公开
    download_count = Column(Integer, default=0)  # 下载次数
    created_at = Column(DateTime, default=datetime.utcnow)

    # 与术语表建立关系
    terms = relationship('Term', backref='term_collection', lazy=True)

    def __repr__(self):
        return f"<TermCollection(table_name={self.table_name}, user_id={self.user_id})>"

    def to_dict(self):
        return {
            'id': self.id,
            'table_name': self.table_name,
            'category': self.category,
            'is_public': self.is_public,
            'download_count': self.download_count
        }


class Term(db.Model):  # change Base to db.Model
    __tablename__ = 'terms'

    id = Column(Integer, primary_key=True, autoincrement=True)
    CN = Column(String, nullable=False)
    EN = Column(String, nullable=False)
    example = Column(String, nullable=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    # 外键，关联到术语集表
    term_collection_id = Column(Integer, ForeignKey('term_collections.id'), nullable=False)

    def __repr__(self):
        return f"<Term(CN={self.CN}, EN={self.EN})>"

    def to_dict(self):
        return {
            'id': self.id,
            'CN': self.CN,
            'EN': self.EN,
            'example': self.example
        }